package com.stonedt.spider.controller;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stonedt.spider.entity.StonedtUser;
import com.stonedt.spider.service.IStonedtUserService;
import com.stonedt.spider.service.LandingUserLogService;
import com.stonedt.spider.util.MD5Util;
import com.stonedt.spider.util.ResultUtil;


@Controller
@RequestMapping("/")
public class StonedtUserController {
	@Autowired
	private IStonedtUserService stonedtUserService;
	@Autowired
	private LandingUserLogService landingUserLogService;
	
	/**
	 * 登录页面
	 * @param mv
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/",produces = "text/plain;charset=utf-8")
	public ModelAndView admin(ModelAndView mv,HttpServletResponse response,HttpServletRequest request){
		
		mv.setViewName("login");
		return mv;
		
	}
	
	/**
	 * 登录验证
	 * @param mv
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/login",produces = "text/plain;charset=utf-8")
	@ResponseBody
	public String login(ModelAndView mv,HttpServletRequest request,HttpSession session){
		String md5Password = MD5Util.getMD5(request.getParameter("password"));
		String result = "";
		/*if("admin".equals(request.getParameter("username"))) {
			StonedtUser user = new StonedtUser();
			user.setUser_name("思通投研");
			user.setId(1);
			user.setUser_username("admin");
			user.setUser_power(1);
			session.setAttribute("User",user);
			result = "{\"code\":1}";
		}else {*/
			StonedtUser cheakUser = stonedtUserService.cheakUser(request.getParameter("username"));
			System.out.println(cheakUser);
			if(cheakUser == null || cheakUser.equals("")) {
				//用户名密码错误
				result = "{\"code\":3}";
			}else {
				if(cheakUser.getUser_password().equals(md5Password) && cheakUser.getUser_status()==1) {
					String username2 = cheakUser.getUser_username();
					System.out.println(username2);
					session.setAttribute("User",cheakUser);
					if(cheakUser.getUser_power() == 1) {
						//管理员登陆成功
						result = "{\"code\":1}";
					}else {
						//普通用户登陆成功
						result = "{\"code\":4}";
					}
					landingUserLogService.save(cheakUser);
				}else if(cheakUser.getUser_status()==2 && cheakUser.getUser_password().equals(md5Password) ){
					//该用户已被停用
					result = "{\"code\":2}";
				}else {
					//用户名密码错误
					result = "{\"code\":3}";
				}
			}
				
		//}
		return result;
	}
	
	/**
	 * 安全退出
	 * @param mv
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/exit",produces = "text/plain;charset=utf-8")
	public ModelAndView exit(ModelAndView mv,HttpServletResponse response,HttpServletRequest request){
		request.getSession().removeAttribute("User");
		request.getSession().removeAttribute("showName");
		mv.setViewName("redirect:/");
		return mv;
	}

	
	/**
	 * 	查询所有用户
	 * @param pagenum
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/userList")
	public ModelAndView getUserAll(ModelAndView mv,
			@RequestParam(value = "pageNum", defaultValue = "1" ,required = false)Integer pagenum,HttpServletRequest request){
		
		PageHelper.startPage(pagenum, 100);
		List<StonedtUser> userAllList = stonedtUserService.queryUserAll();
		PageInfo<StonedtUser> pageInfo = new PageInfo<StonedtUser>(userAllList);

		mv.addObject("list", pageInfo);
		mv.setViewName("user");
		return mv;
	}
	
	/**
	 * 修改用户状态
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/modifyState")
	@ResponseBody
	public Integer modifyState(HttpServletRequest request) {
		String username = request.getParameter("username");
		Integer status = Integer.parseInt(request.getParameter("status"));
		Integer modifyState = null;
		if(username!=null && !"".equals(username)) {
			if(status == 1) {
				//修改用户账号状态
				Integer statu = 2;
				modifyState = stonedtUserService.modifyState(username,statu);
			}else if(status == 2) {
				//修改用户账号状态
				Integer statu = 1;
				modifyState = stonedtUserService.modifyState(username,statu);
			}
		}
		return modifyState;
	}
	
	/**
	 * 删除用户
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/delStonedtUser")
	@ResponseBody
	public Integer delStonedtUser(HttpServletRequest request) {
		String username = request.getParameter("username");
		Integer delStonedtUser = null;
		if(username!=null && !"".equals(username)) {
			delStonedtUser = stonedtUserService.delStonedtUser(username);
		}
		return delStonedtUser;
	}
	
	/**
	 * 重置密码
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/resetPwd")
	@ResponseBody
	public Integer resetPwd(HttpServletRequest request) {
		String username = request.getParameter("username");
		Integer delStonedtUser = null;
		if(username!=null && !"".equals(username)) {
			String password = MD5Util.getMD5("123456");
			delStonedtUser = stonedtUserService.resetPwd(username, password);
		}
		return delStonedtUser;
	}
	
	/**
	 *   添加用户页面
	 * @param mv
	 * @return
	 */
	@RequestMapping(value="/register",produces = "text/plain;charset=utf-8")
	public ModelAndView register(ModelAndView mv){
		mv.setViewName("register");
		return mv;
		
	}
	
	/**
	 *   修改密码界面页面
	 * @param mv
	 * @return
	 */
	@RequestMapping(value="/toupdatePassword",produces = "text/plain;charset=utf-8")
	public ModelAndView toupdatePassword(ModelAndView mv){
		mv.setViewName("updatePassword");
		return mv;
		
	}

	/**
	 *   联系我们界面页面
	 * @param mv
	 * @return
	 */
	@RequestMapping(value="/contactByWX",produces = "text/plain;charset=utf-8")
	public ModelAndView contactByWX(ModelAndView mv){
		mv.setViewName("contactByWX");
		return mv;

	}
	
	/**
	 * @Description:确认密码是否正确
	 * @param username
	 * @return（展示方法参数和返回值）
	 */
	@RequestMapping(value="/checkPassword")
	@ResponseBody
	public ResultUtil checkPassword(HttpServletRequest request,
			@RequestParam(value = "password")String password,
			@RequestParam(value = "user_id")Integer user_id) {
			ResultUtil resultUtil = stonedtUserService.checkPassword(password,user_id);
		return resultUtil;
	}
	
	/**
	 * @Description:确认密码是否正确
	 * @param username
	 * @return（展示方法参数和返回值）
	 */
	@RequestMapping(value="/repassword")
	@ResponseBody
	public ResultUtil repassword(HttpServletRequest request,
			@RequestParam(value = "password")String password,
			@RequestParam(value = "user_id")Integer user_id,
			@RequestParam(value = "repassword")String repassword) {
			ResultUtil resultUtil = stonedtUserService.repassword(password,user_id,repassword);
		return resultUtil;
	}
	
	
	/**
	 * @Description:确认用户是否存在
	 * @param username
	 * @return（展示方法参数和返回值）
	 */
	@RequestMapping(value="/ifUserExist")
	@ResponseBody
	public ResultUtil ifUserExist(HttpServletRequest request,
			@RequestParam(value = "username")String username) {
			ResultUtil resultUtil = stonedtUserService.ifUserExist(username);
		return resultUtil;
	}
	/**
	 *   添加用户
	 * @return
	 */
	@RequestMapping(value="/regist",produces = "application/json; charset=utf-8")
	@ResponseBody
	public String addUser(String username, String password,String name,Integer power,String institution_name){

		System.out.println(name + username + password + power);
		String md5Password = MD5Util.getMD5(password);
		StonedtUser user = new StonedtUser();
		user.setUser_username(username);
		user.setUser_password(md5Password);
		user.setUser_name(name);
		user.setUser_power(power);
		user.setUser_status(1);
		user.setInstitution_name(institution_name);
		int insertUser = stonedtUserService.insertUser(user);
		String result = "";
		if(0 != insertUser) {
			result = "{\"code\":1}";
		}else {
			result = "{\"code\":-1}";
		}
		
		return result;
	}
	
	/**
	 *   官网添加用户
	 * @return
	 */
	@RequestMapping(value="/registStonedt", produces = "application/json; charset=utf-8")
	public @ResponseBody Object addStonedtUser(StonedtUser user,HttpServletRequest request){
		String callback =request.getParameter("callbacka");
		user.setUser_password("e10adc3949ba59abbe56e057f20f883e");
		user.setUser_power(2);
		user.setUser_status(2);
		int insertUser = stonedtUserService.insertUser(user);
		Map<String,Object> map = new HashMap<String,Object>();
		if(0 != insertUser) {
			map.put("msg", "1");
		}else {
			map.put("msg", "-1");
		}
			
		String jsonString = JSON.toJSONString(map);
		
		return callback+ "(" + jsonString + ")";
	}
	
}
